<template />
<script lang="ts" setup>
import {createVNode, nextTick, render} from "vue";
import {mouseWheelScroll} from "@/helper";
import yBar from './yBar.vue'
import xBar from './xBar.vue'

//todo 数据
const props = defineProps({
  el: {type: Object, default: () => null},
  yBarOptions: {type: Object, default: () => ({})},
  xBarOptions: {type: Object, default: () => ({})},
  smooth: { type:Boolean, default: true },
  grain: { type:Number, default: 2 },
})

// todo 方法
nextTick(() => {
  const element = props.el
  if (!element) return console.error('没有找到可滚动的元素')
  element.style.overflow = 'hidden'
  element.style.position = 'relative'
  renderScrollBar(<HTMLElement>element)
  // 监听鼠标滚动
  mouseWheelScroll(<HTMLElement>element, (event: any) => {
    const {wheelDeltaY, wheelDeltaX} = event
    const { scrollLeft,scrollTop } = element
    element.scrollBy({
      top: -wheelDeltaY / Math.abs(props.grain ?? 2),
      left: -wheelDeltaX / Math.abs(props.grain ?? 2),
      behavior: props.smooth ? 'smooth' : 'auto'
    })
  })
  // 监听滚动
  element.addEventListener('scroll', () => {
    yBarNode.component.exposed.renderBar()
    xBarNode.component.exposed.renderBar()
  })
  // 监听窗口变化
  new ResizeObserver(() => {
    yBarNode.component.exposed.renderBar()
    xBarNode.component.exposed.renderBar()
  }).observe(<HTMLElement>element)
})

// 声明节点
let yBarNode:any
let xBarNode:any
/** 渲染滚动条 */
const renderScrollBar = (element:HTMLElement) => {
  yBarNode = createVNode(yBar,{ parentNode:element, barOptions:props.yBarOptions })
  xBarNode = createVNode(xBar,{ parentNode:element, barOptions:props.xBarOptions })
  const tempDom1 = document.createElement('div')
  const tempDom2 = document.createElement('div')
  render(yBarNode, tempDom1)
  render(xBarNode, tempDom2)
  element.appendChild(tempDom1.firstChild)
  element.appendChild(tempDom2.firstChild)

}

</script>